package com.web3.management.controller;

import com.web3.management.dto.ApiResponse;
import com.web3.management.dto.PageResponse;
import com.web3.management.dto.request.CreateAccountConfigRequest;
import com.web3.management.dto.response.AccountConfigDetailResponse;
import com.web3.management.dto.response.AccountConfigHistoryResponse;
import com.web3.management.dto.response.AccountConfigListResponse;
import com.web3.management.dto.response.EffectiveConfigResponse;
import com.web3.management.entity.AccountConfig;
import com.web3.management.security.SecurityUtils;
import com.web3.management.service.AccountConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * 账号配置管理控制器
 *
 * @author Web3 Management Team
 */
@Slf4j
@RestController
@RequestMapping("/api/accounts/{accountId}/configs")
@RequiredArgsConstructor
@Validated
public class AccountConfigController {

    private final AccountConfigService accountConfigService;

    /**
     * 获取账号配置列表
     *
     * @param accountId 账号ID
     * @param page      页码
     * @param size      每页大小
     * @param status    状态筛选
     * @return 配置列表
     */
    @GetMapping
    public ApiResponse<PageResponse<AccountConfigListResponse>> getAccountConfigs(
            @PathVariable @NotNull @Min(1) Integer accountId,
            @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @RequestParam(defaultValue = "10") @Min(1) Integer size,
            @RequestParam(required = false) Integer status) {

        PageResponse<AccountConfigListResponse> response = accountConfigService
                .getAccountConfigs(accountId, page, size, status);

        return ApiResponse.success(response);
    }

    /**
     * 获取账号配置详情
     *
     * @param accountId 账号ID
     * @param configId  配置ID
     * @return 配置详情
     */
    @GetMapping("/{configId}")
    public ApiResponse<AccountConfigDetailResponse> getAccountConfigDetail(
            @PathVariable @NotNull @Min(1) Integer accountId,
            @PathVariable @NotNull @Min(1) Integer configId) {

        AccountConfigDetailResponse response = accountConfigService
                .getAccountConfigDetail(accountId, configId);

        return ApiResponse.success(response);
    }

    /**
     * 获取账号配置历史
     */
    @GetMapping("/{configId}/history")
    public ApiResponse<PageResponse<AccountConfigHistoryResponse>> getAccountConfigHistory(
            @PathVariable @NotNull @Min(1) Integer accountId,
            @PathVariable @NotNull @Min(1) Integer configId,
            @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @RequestParam(defaultValue = "10") @Min(1) Integer size) {

        PageResponse<AccountConfigHistoryResponse> response = accountConfigService
                .getAccountConfigHistory(accountId, configId, page, size);

        return ApiResponse.success(response);
    }

    /**
     * 创建账号配置
     *
     * @param accountId 账号ID
     * @param request   创建请求
     * @return 创建结果
     */
    @PostMapping
    public ApiResponse<Integer> createAccountConfig(
            @PathVariable @NotNull @Min(1) Integer accountId,
            @RequestBody @Valid CreateAccountConfigRequest request) {

        AccountConfig config = accountConfigService.createAccountConfig(accountId, request);

        return ApiResponse.success("账号配置创建成功", config.getId());
    }

    /**
     * 更新账号配置
     *
     * @param accountId 账号ID
     * @param configId  配置ID
     * @param request   更新请求
     * @return 更新结果
     */
    @PutMapping("/{configId}")
    public ApiResponse<String> updateAccountConfig(
            @PathVariable @NotNull @Min(1) Integer accountId,
            @PathVariable @NotNull @Min(1) Integer configId,
            @RequestBody @Valid CreateAccountConfigRequest request) {

        accountConfigService.updateAccountConfig(accountId, configId, request);

        return ApiResponse.success("账号配置更新成功");
    }

    /**
     * 激活账号配置
     *
     * @param accountId 账号ID
     * @param configId  配置ID
     * @return 激活结果
     */
    @PostMapping("/{configId}/activate")
    public ApiResponse<String> activateAccountConfig(
            @PathVariable @NotNull @Min(1) Integer accountId,
            @PathVariable @NotNull @Min(1) Integer configId) {

        accountConfigService.activateAccountConfig(accountId, configId);

        return ApiResponse.success("账号配置已激活");
    }

    /**
     * 删除账号配置
     *
     * @param accountId 账号ID
     * @param configId  配置ID
     * @return 删除结果
     */
    @DeleteMapping("/{configId}")
    public ApiResponse<String> deleteAccountConfig(
            @PathVariable @NotNull @Min(1) Integer accountId,
            @PathVariable @NotNull @Min(1) Integer configId) {

        accountConfigService.deleteAccountConfig(accountId, configId);

        return ApiResponse.success("账号配置已删除");
    }

    /**
     * 获取账号有效配置（合并全局配置）
     *
     * @param accountId 账号ID
     * @return 有效配置
     */
    @GetMapping("/../effective-config")
    public ApiResponse<EffectiveConfigResponse> getEffectiveConfig(
            @PathVariable @NotNull @Min(1) Integer accountId) {

        SecurityUtils.checkAccountAccess(accountId);
        EffectiveConfigResponse response = accountConfigService.getEffectiveConfig(accountId);

        return ApiResponse.success(response);
    }

    /**
     * 从全局配置创建账号配置
     *
     * @param accountId       账号ID
     * @param globalConfigId  全局配置ID
     * @param request         创建请求
     * @return 创建结果
     */
    @PostMapping("/from-global/{globalConfigId}")
    public ApiResponse<Integer> createFromGlobalConfig(
            @PathVariable @NotNull @Min(1) Integer accountId,
            @PathVariable @NotNull @Min(1) Integer globalConfigId,
            @RequestBody CreateFromGlobalRequest request) {

        AccountConfig config = accountConfigService.createFromGlobalConfig(
                accountId, globalConfigId, request.getConfigName(), request.getOverrides());

        return ApiResponse.success("基于全局配置创建成功", config.getId());
    }

    /**
     * 从全局配置创建请求DTO
     */
    public static class CreateFromGlobalRequest {
        private String configName;
        private Map<String, Object> overrides;

        public String getConfigName() {
            return configName;
        }

        public void setConfigName(String configName) {
            this.configName = configName;
        }

        public Map<String, Object> getOverrides() {
            return overrides;
        }

        public void setOverrides(Map<String, Object> overrides) {
            this.overrides = overrides;
        }
    }
}
